<?php

namespace App\Services;
use App\Models\ShortUrlApi;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ShortUrlService
{
    /**
     * 获取
     *
     * @param [type] $agent_id
     * @return void
     */
    public function create($code,$enter_domain){
        $api = ShortUrlApi::show()->inRandomOrder()->first();
        if($api){
            $platform_time = time().'123';
            //防封数据库
            $platform = DB::connection("mysql_ff")->table("platform")->where('domain_link',$enter_domain)->first();
            if(!boolval($platform)){
                $res['code']=-1;
                $res['msg'] = '稍后重试';
                return $res;
            }
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$platform->appid}&redirect_uri=http://{$platform->domain_link}/jump/{$platform_time}/{$platform->id}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            
                //临时长连接
                //  $pla['platform_id']  = $platform->id;
                //  $pla['short_domian'] = $url;
                //  $pla['short_str']    = $platform_time;
                //  $pla['land_domian']  = "?code={$code}";
                 
                //  $resin = Db::connection("mysql_ff")->table('use_record')->insert($pla);
                 
                //  if($resin){
                //      $res['code']=1;
                //      $res['short'] =$url;
                //      $res['long'] = $url;
                //  }else{
                //      $res['code']=-1;
                //      $res['msg'] = '稍后重试';
                //  }
                //  return $res;
                //临时长连接结束

            $api_name = $api->name;
            $data = null;
            if($api_name=='uqm'){
                $data = $this->getUqm($api,$url);
            }else if($api_name=='sinaurl'){
                $data = $this->sina($api,$url);
            }else if($api_name=='r83.net'){
                $data = $this->r83($api,$url);
            }else{
                $res['code']=-1;
                $res['msg'] = '稍后重试';
            }
            if($data['code']==1)
            {
                //同步防封端
                $pla['platform_id']  = $platform->id;
                $pla['short_domian'] = $data['short'];
                $pla['short_str']    = $platform_time;
                $pla['land_domian']  = "?code={$code}";
                
                $resin = Db::connection("mysql_ff")->table('use_record')->where('short_domian',$data['short'])->exists();
                if($resin){
                    $res['code']=-1;
                    $res['msg'] = '稍后重试';
                    return $res;
                }
                
                $resin = Db::connection("mysql_ff")->table('use_record')->insert($pla);
                
                if($resin){
                    $res['code']=1;
                    $res['short'] = $data['short'];
                    $res['long'] = $url;
                }else{
                    $res['code']=-1;
                    $res['msg'] = '稍后重试';
                }
                return $res;
            }else{
                $res['code']=-1;
                $res['msg'] = $data['msg'];
            }
            return $res;
        }else{
            $res['code']=-1;
            $res['msg'] = '网关不存在';
            return $res;
        }
    }


    /**
     * 获取网关
     */
    protected function getApi($api_id){
        $api = ShortUrlApi::show()->find($api_id);
        if(boolval($api)){
            return $api;
        }else{
            return null;
        }
    }

    /**
     * 生成uqm短网址
     */
    protected function getUqm($api,$url){
        $token = $api->apikey;
        $geturl =  $api->api;
        $param = http_build_query([
            'token'     =>  $token
            ,'longurl'  =>  $url
            ,'format'   =>  'json'
        ]);
        $opts       = [
            'http'        =>  array(  
                'method'    =>  "POST",  
                'header'    =>  "Content-type: application/x-www-form-urlencoded\r\n".  
                    "Content-length:".strlen($param)."\r\n" .   
                    "Cookie: foo=bar\r\n" .   
                    "\r\n",  
                'content'   => $param,  
            ),
            "ssl" => array(
                "verify_peer"       =>  false,
                "verify_peer_name"  =>  false,
            )
        ];
        $dwz = file_get_contents($geturl, $param, stream_context_create($opts));
        $data =json_decode($dwz);
        $res['code']=-1;
        $res['short']='';
        $res['msg'] = '';
        if($data->code==1){
            $res['code']=1;
            $res['short'] = $data->short;
        }else{
            $res['code']=-1;
            $res['msg'] = $data->msg;
        }
        return $res;
    }

     /**
     * 生成新浪短网址
     */
    protected function sina($api,$url){
        $geturl = $api->api;
        $geturl .=urlencode($url);
        $res['code']=-1;
        $res['short']='';
        $res['msg'] = '';
        $dwz = file_get_contents($geturl);
        $data =json_decode($dwz);
        if($data->statu!=true){
            $res['code']=-1;
            $res['msg'] = '生成失败，请重试';
        }else{
            $res['code']=1;
            $res['short'] = $data->short;
        }
        return $res;
    }

         /**
     * 生成r83短网址
     */
    protected function r83($api,$url){
        $geturl = $api->api;
        $geturl .=urlencode($url);
        $res['code']=-1;
        $res['short']='';
        $res['msg'] = '';
        $dwz = file_get_contents($geturl);
        $data =json_decode($dwz);
        if(boolval($data->err)){
            $res['code']=-1;
            $res['msg'] = $data->err;
        }else{
            $res['code']=1;
            $res['short'] = $data->url;
        }
        return $res;
    }
}